package com.qf.smsplatform.strategy.strategy.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StragetyConstents;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: sms-platform
 *
 * @author: 黄睿武
 * time: 2021/8/13 19:40
 * description:
 */


/**
 * 1小时限流策略校验
 */
@Service(value = "limitOneHour")
@Slf4j
public class LimitOneHourStrategyImpl implements Strategy {

    @Autowired
    private CacheClient cacheClient;

    /**
     * 所有策略模块必须有的一个方法,用于校验或补全短信内容(submit对象)
     *
     * @param submit 短信内容
     * @return true代表通过, false校验未通过
     */
    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-1小时限流策略]  开始执行.......");
        //1小时内发送次数不能大于5条
        String key = CacheConstants.CACHE_PREFIX_SMS_LIMIT + submit.getClientID() +":" + submit.getDestMobile();
        long max = System.currentTimeMillis();
        long min = max - (60*1000*60);
        int count = cacheClient.zRangeByScore(key,min,max);
        if(count >= 5 ){

            log.info("[策略模块-1小时限流策略] 1小时内发送短信次数超过5条,不能再发送.......");

            //发日志和报告
            PushErrorMessageUtil.sendLog(submit, StragetyConstents.STRATEGY_ERROR_LIMIT);
            Integer isreturnstatus = Integer.valueOf(cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "isreturnstatus"));
            if(isreturnstatus == 1){
                PushErrorMessageUtil.sendReport(submit,StragetyConstents.STRATEGY_ERROR_LIMIT);
            }

            return false;
        }


        log.info("[策略模块-1小时限流策略]  执行成功.......");
        return true;
    }
}
